<template>
  <div class="col-md-8">
    <h3 class="reply">评论回复：</h3>
    <h2 v-if="!comments.length">暂无评论，点击左侧添加评论！！！</h2>
    <ul class="list-group">
      <CommentItem
        v-for="comment in comments"
        :key="comment.id"
        :comment="comment"
        :delComment="delComment"
      />
    </ul>
  </div>
</template>

<script>
import CommentItem from "./CommentItem";

export default {
  name: "CommentList",
  components: {
    CommentItem,
  },
  // 哪里需要数据展示，数据源就定义在哪
  data() {
    return {
      // 定义数据
      comments: [
        {
          id: 1,
          username: "peihua",
          content: "i like haijing",
        },
        {
          id: 2,
          username: "haijing",
          content: "i like dianlei",
        },
      ],
    };
  },
  // 数据源在哪？更新数据的方法就在那
  methods: {
    // 定义更新数据的方法
    addComment(username, content) {
      this.comments.unshift({
        id: Date.now(),
        username,
        content,
      });
    },
    delComment(id) {
      // filter方法内函数返回值true代表保留，false代表过滤
      this.comments = this.comments.filter((comment) => comment.id !== id);
    },
  },
  mounted() {
    this.$bus.$on("addComment", this.addComment);
  },
  beforeDestroy() {
    this.$bus.$off("addComment", this.addComment);
  },
};
</script>

<style>
.reply {
  margin-top: 0px;
}
</style>